package cn.easy.rpc.beans;
import cn.easy.rpc.annotations.RpcReference;
import cn.easy.rpc.context.RpcContext;
import cn.easy.rpc.proxy.RpcProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

/**
 * @author zwb
 * @create 2020-09-17 21:54
 **/
@Component
public class RpcInjectPostProcessor implements BeanPostProcessor{

    private RpcContext rpcContext = RpcContext.getInstance();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        ReflectionUtils.doWithFields(bean.getClass(),(field) ->{
            RpcReference rpcReference;
            if((rpcReference = field.getDeclaredAnnotation(RpcReference.class)) != null){
                ReflectionUtils.makeAccessible(field);
                ReflectionUtils.setField(field,bean,RpcProxy.create(field.getType(),rpcReference));
            }
        });

        return bean;
    }
}
